package com.zscat.mallplus.dms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.douyin.open.api.ToutiaoClientTokenApi;
import com.douyin.open.models.ToutiaoOauth2Oauth2InlineResponse2002;
import com.jpay.util.StringUtils;
import com.zscat.mallplus.dms.service.IQsgStoreService;
import com.zscat.mallplus.qsg.QsgStore;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.List;


public class DouyinTokenTask extends QuartzJobBean {
    @Autowired
    private IQsgStoreService storeService;

    @Value("${douyin.server.storeid}")
    private Integer storeId;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        List<QsgStore> stores = storeService.list(new QueryWrapper<>());
        QsgStore serverStore = storeService.getById(storeId);
        String accessToken = "";
        if (StringUtils.isNotBlank(serverStore.getDouyinAppid()) && StringUtils.isNotBlank(serverStore.getDouyinSecret())) {
            String clientKey = serverStore.getDouyinAppid();
            String clientSecret = serverStore.getDouyinSecret();
            String grantType = "client_credential";
            ToutiaoClientTokenApi api = new ToutiaoClientTokenApi();
            ToutiaoOauth2Oauth2InlineResponse2002 response = api.oauthClientTokenGet(clientKey, clientSecret, grantType);
            Integer errorCode = response.getData().getErrorCode();
            if (errorCode == 0) {
                accessToken = response.getData().getAccessToken();
            }
        }
        for (QsgStore store : stores) {
            store.setDouyinToken(accessToken);
            storeService.updateById(store);
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("private_douyin",1);
        List<QsgStore> qsgStores = storeService.list(queryWrapper);
        if (null != qsgStores && !qsgStores.isEmpty()){
            for (QsgStore store : qsgStores){
                String key = store.getDouyinAppid();
                String secret = store.getDouyinSecret();
                String type = "client_credential";
                ToutiaoClientTokenApi tokenApi = new ToutiaoClientTokenApi();
                ToutiaoOauth2Oauth2InlineResponse2002 toutiaoResponse = tokenApi.oauthClientTokenGet(key, secret, type);
                Integer errCode = toutiaoResponse.getData().getErrorCode();
                if (errCode == 0) {
                    String dandianToken = toutiaoResponse.getData().getAccessToken();
                    store.setDouyinToken(dandianToken);
                    storeService.updateById(store);
                }
            }
        }
    }
}
